using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Data.SqlClient;
using System.Net.Mail;

public partial class Default2 : System.Web.UI.Page
{
    bool CanshowBCC = false;
    string strfrmEmailID = "";
    string strMessage = "";
    DataSet dsEmail = new DataSet();
    string strEmailField = "";
    string strToAddress = "";
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        security hdds = new security();
        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

        if (!Page.IsPostBack)
        {

            DynamicDisplayI DDI = new DynamicDisplayI();

            DDI.setAttribute(lnkCC.Attributes, "onclick", "javascript:ShowHidePanel('tblCC','lnkCC','CC','txtCC');");
            DDI.setAttribute(lnkBCC.Attributes, "onclick", "javascript:ShowHidePanel('tblBCC','lnkBCC','BCC','txtBCC');");
            DDI.setAttribute(lnkAttach.Attributes, "onclick", "javascript:ShowHidePanel('tblAttachments','lnkAttach','','FileUpload1');");
            DDI.setAttribute(txtTo.Attributes, "onblur", "javascript:UpdateRelatedTo();");
            //lnkCC.Attributes.Add("onclick", "javascript:ShowHidePanel('tblCC','lnkCC','CC','txtCC');");
            //lnkBCC.Attributes.Add("onclick", "javascript:ShowHidePanel('tblBCC','lnkBCC','BCC','txtBCC');");
            //lnkAttach.Attributes.Add("onclick", "javascript:ShowHidePanel('tblAttachments','lnkAttach','','FileUpload1');");
            //txtTo.Attributes.Add("onblur", "javascript:UpdateRelatedTo();");
            ReEnableButtons();
            DDI = null;
        }

        dsEmail = GetEmailPageData();

        string url = Navigator.getURL(HttpContext.Current.Request.Url.ToString());

        if (!Page.IsPostBack)
        {
            HidePanels();
            if (CanShowBCC(dsEmail))
            {
                lnkBCC.Visible = true;
                LoadBCCDefaultValue(dsEmail);
            }
            SetFromEmailID(dsEmail);
            LoadDefaultSignature(dsEmail);
            LoadRelatedTo();

            
        }

        if (Request.QueryString != null)
        {
            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["pgs_id"] != null)
                {
                    string strPK = Request.QueryString["PK"].ToString();
                    string strpgs_id = Request.QueryString["pgs_id"].ToString();
                    strEmailField = Request.QueryString["CnID"].ToString();
                    imgsearch.Attributes.Add("onclick", "javascript:OpenLookup('hfTo','txtTo','" + strEmailField + "','" + strPK + "','" + strpgs_id + "');");
                }
                else
                {
                    imgsearch.Visible = false;
                }
            }
            else imgsearch.Visible = false;
        }
        else
        {
            imgsearch.Visible = false;
        }
    }

    /// <summary>
    /// Gets all datas requried for Email page in this dataset
    /// </summary>
    /// <returns></returns>
    private DataSet GetEmailPageData()
    {
        DataSet dsResult = new DataSet();
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (Session["user_afrowid"] != null)
            {

                string strPagesetRowId = "";
                if (Request.QueryString["pgs_id"] != null)
                    strPagesetRowId = Request.QueryString["pgs_id"].ToString();

                PageInfoLoad PIL = new PageInfoLoad();
                dsResult = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);

                string sql = "select * from sy_my_email_settings where owner_id = '" + Session["user_afrowid"].ToString() + "' order by modified_at desc";
                DataTable dt = HDD.GetDataTable(sql,"my_email_settings");
                if (dt != null)
                    dsResult.Tables.Add(dt.Copy());
                
                sql = "select * From sy_acr_mem where af_row_id = '5fa71c28f7a6518a'";
                dt = HDD.GetDataTable(sql,"DefaultFromEmail");
                if (dt != null)
                    dsResult.Tables.Add(dt.Copy());

                sql = "select * from sy_obj A, sy_pgs B, sy_pgs_mem C where B.af_row_id = C.pageset_id and C.object_id = A.object_id and B.af_row_id = '" + strPagesetRowId + "'";
                dt = HDD.GetDataTable(sql,"Objects");
                if (dt != null)
                    dsResult.Tables.Add(dt.Copy());


                

            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetEmailPageData : "+ ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return dsResult;
    }

    private bool CanShowBCC(DataSet ds)
    {
        bool status = false;
        try
        {
            if (ds.Tables.Count > 0)
                if (ds.Tables["my_email_settings"] != null)
                {
                    DataTable dt = ds.Tables["my_email_settings"];
                    if (dt.Rows.Count > 0)
                        status = dt.Rows[0]["enable_bcc"].ToString().Trim() != "" ? Convert.ToBoolean(dt.Rows[0]["enable_bcc"].ToString()) : false;
                    CanshowBCC = status;
                }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : CanShowBCC :"+ ex.Message);
        }
        return status;
    }
    private void LoadBCCDefaultValue(DataSet ds)
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        try
        {
            if (CanshowBCC)
            {
                if (ds != null)
                    if (ds.Tables.Count > 0)
                        if (ds.Tables["my_email_settings"] != null)
                        {
                            DataTable dt = ds.Tables["my_email_settings"];
                            if (dt.Rows.Count > 0)
                                if (dt.Rows[0]["email"].ToString().Trim() != "")
                                {
                                    txtBCC.Text = dt.Rows[0]["email"].ToString();
                                    //DDI.setAttribute(lnkBCC.Attributes, "onclick", "javascript:SetBCCText('"+dt.Rows[0]["email"].ToString()+"')");
                                    strfrmEmailID = dt.Rows[0]["email"].ToString();
                                }
                            //else
                            //{
                            //    if (ds.Tables["DefaultFromEmail"] != null)
                            //    {
                            //        DataTable dtEmail = ds.Tables["DefaultFromEmail"];
                            //        if (dtEmail.Rows.Count > 0)
                            //            txtBCC.Text = dtEmail.Rows[0]["mem_value1"].ToString();
                            //    }
                            //}
                        }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : LoadBCCDefaultValue : " + ex.Message);
        }
        finally
        {
            DDI = null;
        }
    }

    private void SetFromEmailID(DataSet ds)
    {
        try
        {
            if (ds != null)
                if (ds.Tables.Count > 0)
                    if (ds.Tables["my_email_settings"] != null)
                    {
                        DataTable dt = ds.Tables["my_email_settings"];
                        if (dt.Rows.Count > 0)
                        {
                            if (dt.Rows[0]["email"].ToString().Trim() != "")
                            {
                                txtFrom.Text = dt.Rows[0]["email"].ToString();

                                if (dt.Rows[0]["display_name"].ToString().Trim() != "")
                                {
                                    txtFrom.Text = dt.Rows[0]["display_name"].ToString() + "<" + txtFrom.Text + ">";
                                }

                            }
                            else
                            {
                                if (ds.Tables["DefaultFromEmail"] != null)
                                {
                                    DataTable dtEmail = ds.Tables["DefaultFromEmail"];
                                    if (dtEmail.Rows.Count > 0)
                                    {
                                        txtFrom.Text = dtEmail.Rows[0]["mem_value1"].ToString();
                                        if (dtEmail.Rows[0]["mem_value2"].ToString().Trim() != "")
                                        {
                                            txtFrom.Text = dtEmail.Rows[0]["mem_value2"].ToString() + "<" + txtFrom.Text + ">";
                                        }
                                    }

                                }
                            }
                        }
                        else
                        {
                            if (ds.Tables["DefaultFromEmail"] != null)
                            {
                                DataTable dtEmail = ds.Tables["DefaultFromEmail"];
                                if (dtEmail.Rows.Count > 0)
                                {
                                    txtFrom.Text = dtEmail.Rows[0]["mem_value1"].ToString();
                                    if (dtEmail.Rows[0]["mem_value2"].ToString().Trim() != "")
                                    {
                                        txtFrom.Text = dtEmail.Rows[0]["mem_value2"].ToString() + "<" + txtFrom.Text + ">";
                                    }
                                }

                            }
                        }
                    }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : SetFromEmailID :"+ ex.Message);
        }
    }
    protected void btnSendTop_Click(object sender, EventArgs e)
    {
        SendEmail();

    }
    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
    private bool SendEmail()
    {
        bool status = false;
        ScreenReader SR = new ScreenReader();
        string af_row_id = SR.getHashKey();
        string strstatus = "";
        string strerrormsg = "";
        string message = "";
        string strBCC = "";
        try
        {
            if (CheckIfBCCExists())
                strBCC = txtBCC.Text;

            //if (txtBCC.Text.Trim() != "")
            //    strBCC = txtBCC.Text;

            if (validFile())
            {
                if (ValidateAttachments())
                {
                    if (Request.QueryString["pgs_id"] == null)
                    {
                        if (Request.QueryString["PK"] == null)
                        {
                            CommonFunctions cf = new CommonFunctions();
                            byte[] content = ConvertAttachmentToByte(FileUpload1);
                            //string result = cf.sendEmail(txtTo.Text, txtFrom.Text, true, txtSubject.Text, txtBody.Text, content, FileUpload1.FileName, cf.UseCompanyEmailServerSettings(), txtCC.Text, txtBCC.Text);
                            string strbody = txtBody.Text;
                            string result = cf.SendEmailBasedOnConfig(txtTo.Text, txtFrom.Text, false, txtSubject.Text, strbody, content, FileUpload1.FileName, txtCC.Text, strBCC);

                            //MailAddress[] toaddress = new MailAddress[2];
                            //MailAddress add = new MailAddress("srsrivatsan@gmail.com", "");
                            //MailAddress add1 = new MailAddress("srivatsan_ramadesikan@cellarstone.com", "Srivatsan2");
                            //toaddress[0] = add;
                            //toaddress[1] = add1;
                            //Hashtable ht = new Hashtable();
                            //ht.Add("Sri", "srsrivatsan@gmail.com");
                            //ht.Add("Srivatsan", "srivatsan_ramadesikan@cellarstone.com");
                            // string result = cf.sendMail(ht, txtFrom.Text,false, txtSubject.Text, strbody, content, FileUpload1.FileName, txtCC.Text, txtBCC.Text,false);

                            if (result == "success")
                            {
                                status = true;
                                message = wrapItAsMessage("<img src=\"Images/tick5.gif\" alt=\"Success\"></img>&nbsp; Mail sent Successfully",false);
                            }
                            else
                            {
                                message = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp; Error: " + HttpUtility.HtmlEncode(message),true);
                            }
                            lblmessage.Text = message;
                        }
                    }
                    else
                    {
                        string tablename = GetTableName(Request.QueryString["pgs_id"].ToString());
                        string firstfield = FirstFieldID(Request.QueryString["pgs_id"].ToString());

                        if (ValidateEmailID(firstfield, tablename))
                        {
                            UpdateRelatedTo();
                            LogEmail(FileUpload1.FileName, af_row_id, strBCC);
                            byte[] content = ConvertAttachmentToByte(FileUpload1);
                            CommonFunctions cf = new CommonFunctions();
                            string toaddress = txtTo.Text + "<" + hfTo.Value + ">";
                            //                    string result = cf.sendEmail(toaddress, txtFrom.Text, true, txtSubject.Text, txtBody.Text, content, FileUpload1.FileName, cf.UseCompanyEmailServerSettings(), txtCC.Text, txtBCC.Text);
                            string strbody = txtBody.Text;
                            //if (strbody.Contains("\r\n"))
                            //    strbody = strbody.Replace("\r\n", "<br\\>");
                            string result = cf.SendEmailBasedOnConfig(toaddress, txtFrom.Text, false, txtSubject.Text, strbody, content, FileUpload1.FileName, txtCC.Text, strBCC);
                            if (result == "success")
                            {
                                CreateNotesRecord(Request.QueryString["PK"].ToString(), dsEmail, strBCC);
                                SaveAttachmentsinDocument(Request.QueryString["PK"].ToString()); // Parameter added by 'Imran Gani' on 23-Nov-12, for related row id.
                                status = true;
                                message = wrapItAsMessage("<img src=\"Images/tick5.gif\" alt=\"Success\"></img>&nbsp; Mail sent Successfully",false);
                                //btnSend.Enabled = false;
                                //btnSendTop.Enabled = false;
                                btnSend.Attributes.Add("disabled", "true");
                                btnSendTop.Attributes.Add("disabled", "true");

                                strstatus = "Mail Sent Successfully";
                                strerrormsg = "";
                            }
                            else
                            {
                                message = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp; Error: " + HttpUtility.HtmlEncode(result),true);
                                strstatus = "Mail Not Sent";
                                strerrormsg = result;
                            }
                            strMessage = result;
                            lblmessage.Text = message;


                        }
                        else
                        {
                            lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp; Error: " + HttpUtility.HtmlEncode(txtTo.Text) + " does not exits in To Lookup",true);
                            return false;
                        }
                        
                    }
                }
                else
                {
                    lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp; Error: Exceeded the file attachment size limit of 4 MB",true);
                    return false;
                }
            }
            else 
            {
                lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp; Error: Attached file type not supported",true);
                return false; 
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SendEmail :" + ex.Message);
            lblmessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp; Error: " + HttpUtility.HtmlEncode(ex.Message),true);
        }
        finally
        {
            UpdateEmailLog(af_row_id, strstatus,strerrormsg);
            ReEnablePanels();
        }   
        return status;
    }
    private byte[] ConvertAttachmentToByte(FileUpload fileupload)
    {
        byte[] result = null;
        try
        {
            if (fileupload.HasFile)
            {
                BinaryReader br = new BinaryReader(fileupload.PostedFile.InputStream);
                result = br.ReadBytes(fileupload.PostedFile.ContentLength);
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : ConvertAttachementToByte :"+ ex.Message);
        }
        return result;
    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        SendEmail();
    }

    private void LoadDefaultSignature(DataSet ds)
    {
        try
        {
            if(ds!=null)
                if(ds.Tables.Count>0)
                    if (ds.Tables["my_email_settings"] != null)
                    {
                        DataTable dt = ds.Tables["my_email_settings"];
                        if (dt.Rows.Count > 0)
                        {
                            string strsign = "\r\n\r\n\r\n"+dt.Rows[0]["email_signature"].ToString();
                            txtBody.Text = strsign;
                        }
                    }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : LoadDefaultSignature :"+ ex.Message);
        }
    }

    private void LoadRelatedTo()
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (Request.QueryString["PK"] != null)
                if(Request.QueryString["CnID"]!=null)
                    if (Request.QueryString["pgs_id"] != null)
                    {
                        string strPK = "";
                        if (dsEmail.Tables["PageKeys"].Rows.Count > 0)
                        {
                            if (Request.QueryString["MK"] != null)
                            {
                                strPK = Request.QueryString["MK"].ToString();
                            }
                            else if (Request.QueryString["PK"] != null)
                            {
                                strPK = Request.QueryString["PK"].ToString();
                            }
                        }
                        else
                            strPK = Request.QueryString["PK"].ToString();
                        string strPagesetRowId = Request.QueryString["pgs_id"].ToString();
                        string strcontrolid = Request.QueryString["CnID"].ToString();

                        string TableName = GetTableName(strPagesetRowId);
                        string strfirstfield = FirstFieldID(strPagesetRowId);
                        string PageName = GetObjectName(strPagesetRowId);
                        string sql = "select "+strcontrolid+" as EF,"+strfirstfield+" as FF from "+TableName+" where af_row_id = '"+strPK+"'";
                        DataTable dt = HDD.GetDataTable(sql); 
                        if(dt!=null)
                            if (dt.Rows.Count > 0)
                                if (dsEmail != null)
                                {
                                    DataRow drPageKeys = null;
                                    if (dsEmail.Tables["PageKeys"] != null)
                                        if (dsEmail.Tables["PageKeys"].Rows.Count > 0)
                                            drPageKeys = dsEmail.Tables["PageKeys"].Rows[0];
                                    if (drPageKeys!=null)
                                    {
                                        string displaytext = "";
                                        string strObjectid = drPageKeys["master_obj"].ToString();
                                        string strdisplayfield = drPageKeys["display_att"].ToString();
                                        sql = "select object_table from sy_obj where object_id = '" + strObjectid + "'";
                                        sql = "select " + strdisplayfield + " from " + HDD.GetColumnValue(sql) + " where af_row_id='" + dt.Rows[0]["FF"].ToString() + "'";
                                        displaytext = HDD.GetColumnValue(sql);

                                        string result = PageName + " : " + displaytext;
                                        txtRelatedTo.Text = result;
                                        hfTo.Value = dt.Rows[0]["EF"].ToString();
                                        txtTo.Text = displaytext;
                                        strToAddress = txtTo.Text + "<" + hfTo.Value + ">";
                                    }
                                    else
                                    {
                                        string result = PageName + " : " + dt.Rows[0]["FF"].ToString();
                                        txtRelatedTo.Text = result;
                                        hfTo.Value = dt.Rows[0]["EF"].ToString();
                                        txtTo.Text = dt.Rows[0]["FF"].ToString();
                                        strToAddress = txtTo.Text + "<" + hfTo.Value + ">";
                                    }
                                }
                    }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : LoadRelatedTo :"+ ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }
    private string GetTableName(string strPagesetRowId)
    {
        string result = "";
        HDDatabase HDD = null;
        try
        {
            if (strPagesetRowId.Trim() != "")
            {
                HDD = new HDDatabase();
                string sql = "select C.page_table_name from sy_pgs A, sy_pgs_mem B , sy_pg C where A.af_row_id = B.pageset_id and B.page_id = C.page_id and A.af_row_id = '" + strPagesetRowId + "'";
                result = HDD.GetColumnValue(sql);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetTableName :" + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return result;
    }
    private string FirstFieldID(string strPagesetRowId)
    {
        string result = "";
        HDDatabase HDD = new HDDatabase();
        try
        {
            string sql = "select control_id from sy_pgs A, sy_pgs_mem B , sy_pg C,sy_pg_ctr D where A.af_row_id = B.pageset_id and B.page_id = C.page_id and C.af_row_id = D.page_id and D.control_visible =1 and A.af_row_id = '" + strPagesetRowId + "'  order by control_seq asc";
            result = HDD.GetColumnValue(sql);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : FirstFieldID :" + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return result;
    }

    private string GetObjectName(string strPagesetRowId)
    {
        string result = "";
        HDDatabase HDD = new HDDatabase();
        try
        {
            //string sql = "select C.page_name from sy_pgs A, sy_pgs_mem B , sy_pg C where A.af_row_id = B.pageset_id and B.page_id = C.page_id and A.pageset_id = '" + strPagesetRowId + "'";
            string sql = "select object_name from sy_obj A, sy_pgs B, sy_pgs_mem C where B.af_row_id = C.pageset_id and C.object_id = A.object_id and B.af_row_id = '" + strPagesetRowId + "'";
            result = HDD.GetColumnValue(sql);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : FirstFieldID :" + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return result;
    }

    private bool CreateNotesRecord(string related_af_row_id,DataSet ds,string strBCC)
    {
        bool status = false;
        ScreenReader SR = new ScreenReader();
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (CanAddNotes(ds))
            {
                string title = txtSubject.Text + " [Email]";
                string object_af_row_id = ds.Tables["Objects"].Rows[0]["af_row_id"].ToString();
                string notes = GetNotesText(strBCC);
                string insertsql = "insert into [sy_notes] ([related_object_id],[related_af_row_id],[title],[notes],[af_row_id],[created_by],[created_at],[modified_at],[modified_by],[owner_id],[notes_date]) values ('" + object_af_row_id.Replace("'","''") + "','" + related_af_row_id.Replace("'","''") + "','" + title.Replace("'","''") + "','" + notes.Replace("'","''") + "','" + SR.getHashKey() + "','" + Session["user_afrowid"].ToString() + "','" + DateTime.UtcNow + "','" + DateTime.UtcNow + "','" + Session["user_afrowid"].ToString() + "','" + Session["user_afrowid"].ToString() + "','" + DateTime.UtcNow + "');";
                int rows = HDD.ExecuteCmdObj(new SqlCommand(insertsql));
                if (rows > 0)
                {
                    status = true;
                }
            }
            else
            {
                status = true;
            }

        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : CreateNotesRecord : "+ ex.Message);
        }
        return status;
    }

    private string GetNotesText(string strBCC)
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            sb.AppendLine("From : " + txtFrom.Text);
            sb.AppendLine("To : " + txtTo.Text + "<" + hfTo.Value + ">");
            sb.AppendLine("Related To : "+ txtRelatedTo.Text);
            sb.AppendLine("CC : "+ txtCC.Text);
            sb.AppendLine("BCC : "+ strBCC);
            if (validFile()) // Added by 'Imran Gani' on 23-Nov-12, for attached document.
            {
                if (FileUpload1.HasFile)
                {
                    sb.AppendLine("Attachment : " + FileUpload1.FileName.ToString().Substring(0, FileUpload1.FileName.ToString().IndexOf(".")));
                }
            }
            sb.AppendLine("Subject : "+ txtSubject.Text);
            sb.AppendLine("");
            sb.AppendLine("Body : ");
            sb.AppendLine(txtBody.Text);
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetNotesText :"+ ex.Message);
        }
        return sb.ToString();
    }

    private bool CanAddNotes(DataSet ds)
    {
        bool status = false;
        try
        {
            if (ds != null)
                if (ds.Tables["Objects"] != null)
                    if (ds.Tables["Objects"].Rows.Count > 0)
                        status = ds.Tables["Objects"].Rows[0]["associate_notes"].ToString().Trim() != "" ? Convert.ToBoolean(ds.Tables["Objects"].Rows[0]["associate_notes"].ToString().Trim()) : false;
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : CanAddNotes : " + ex.Message);
        }
        return status;
    }
    private bool LogEmail(string strAttachName,string af_row_id,string strBCC)
    {
       bool status = false;
        HDDatabase HDD = new HDDatabase();
        try
        {
            if(Session["user_afrowid"]!=null)
            {
            string sql = "select * from sy_emails where owner_id = '"+Session["user_afrowid"].ToString()+"'";
            string toaddress = txtTo.Text + "<" + hfTo.Value + ">";
            DataTable dt = HDD.GetDataTable(sql);
            if (dt.Rows.Count == 0)
            {
                //string sql = "insert into [sy_emails] ([from_address],[to_address],[additional_to],[related_to],[cc_address],[bcc_address],[subject],[body],[attachments],[start_time],[end_time],[status],[af_row_id],[created_by],[created_at],[modified_at],[modified_by],[owner_id],[sending_user],[last_error],[last_attempted_at]) values ('" + txtFrom.Text + "','" + toaddress + "','" + txtAdditionalTo.Text + "','" + txtRelatedTo.Text + "','" + txtCC.Text + "','" + txtBCC.Text + "','" + txtSubject.Text + "','" + txtBody.Text + "','" + strAttachName + "','" + DateTime.UtcNow + "',null,null,'" + af_row_id + "','" + Session["user_afrowid"].ToString() + "','" + DateTime.UtcNow + "','" + DateTime.UtcNow + "','" + Session["user_afrowid"].ToString() + "','" + Session["user_afrowid"].ToString() + "','" + Session["userid"].ToString() + "')";
                sql = "insert into [sy_emails] ([from_address],[to_address],[additional_to],[related_to],[cc_address],[bcc_address],[subject],[body],[attachments],[start_time],[end_time],[status],[af_row_id],[created_by],[created_at],[modified_at],[modified_by],[owner_id],[last_error],[last_attempted_at],[email_attempts]) values ('" + txtFrom.Text.Replace("'", "''") + "','" + toaddress.Replace("'", "''") + "','" + txtAdditionalTo.Text.Replace("'", "''") + "','" + txtRelatedTo.Text.Replace("'", "''") + "','" + txtCC.Text.Replace("'", "''") + "','" + strBCC.Replace("'", "''") + "','" + txtSubject.Text.Replace("'", "''") + "','" + txtBody.Text.Replace("'", "''") + "','" + strAttachName.Replace("'", "''") + "','" + DateTime.UtcNow + "','" + DateTime.UtcNow + "',null,'" + af_row_id + "','" + Session["user_afrowid"].ToString() + "','" + DateTime.UtcNow + "','" + DateTime.UtcNow + "','" + Session["user_afrowid"].ToString() + "','" + Session["user_afrowid"].ToString() + "',null,'" + DateTime.UtcNow + "',1)";
                int cnt = HDD.ExecuteCmdObj(new SqlCommand(sql));
                if (cnt > 0)
                    status = true;
            }
            else
            {
                int attempts = dt.Rows[0]["email_attempts"].ToString().Trim() != "" ? Convert.ToInt32(dt.Rows[0]["email_attempts"].ToString().Trim())+1 : 1;
                sql = "update sy_emails set from_address = '" + txtFrom.Text.Replace("'", "''") + "', to_address = '" + toaddress.Replace("'", "''") + "',additional_to='" + txtAdditionalTo.Text.Replace("'", "''") + "',related_to='" + txtRelatedTo.Text.Replace("'", "''") + "',cc_address='" + txtCC.Text.Replace("'", "''") + "',bcc_address='" + strBCC.Replace("'", "''") + "',subject='" + txtSubject.Text.Replace("'","''") + "',body='" + txtBody.Text.Replace("'", "''") + "',attachments='" + strAttachName.Replace("'","''") + "',start_time='" + DateTime.UtcNow + "',end_time='" + DateTime.UtcNow + "',status=null,[modified_at]='" + DateTime.UtcNow + "',[modified_by]='" + Session["user_afrowid"].ToString() + "',owner_id='" + Session["user_afrowid"].ToString() + "',last_attempted_at='"+DateTime.UtcNow+"',email_attempts="+attempts+" where owner_id = '"+Session["user_afrowid"].ToString()+"'";
                int cnt = HDD.ExecuteCmdObj(new SqlCommand(sql));
                if (cnt > 0)
                    status = true;
            }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : LogEmail :" + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return status;
    }
    private bool UpdateEmailLog(string af_row_id, string strstatus,string errormsg)
    {
        bool status = false;
        HDDatabase HDD = new HDDatabase();
        try
        {
            if (Session["user_afrowid"] != null)
            {
                string sql = "update sy_emails set status = '" + strstatus.Replace("'","''") + "', end_time ='" + DateTime.UtcNow + "',last_error = '"+errormsg.Replace("'","''")+"' where owner_id = '" + Session["user_afrowid"].ToString() + "'";
                int count = HDD.ExecuteCmdObj(new SqlCommand(sql));
                if (count > 0)
                    status = true;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : UpdateEmailLog :" + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return status;
    }

    private bool SaveAttachmentsinDocument(string related_af_row_id) // Parameter added by 'Imran Gani' on 23-Nov-12.
    {
        bool status = false;
        HDDatabase HDD = new HDDatabase();
        ScreenReader SR = new ScreenReader();
        try
        {
            if (validFile())
            {
                if (FileUpload1.HasFile)
                {
                    string filename = FileUpload1.FileName.ToString().Substring(0, FileUpload1.FileName.ToString().IndexOf("."));
                    int len = FileUpload1.PostedFile.ContentLength;
                    string af_row_id = SR.getHashKey();

                    byte[] filea = new byte[len];
                    FileUpload1.PostedFile.InputStream.Read(filea, 0, len);

                    string sql = "insert into [sy_documents] ([name],[description],[file_type],[file_size],[file_name],[download_url],[af_row_id],[created_by],[created_at],[modified_at],[modified_by],[fileContent],[owner_id],[related_af_row_id]) values ('" + txtSubject.Text.Replace("'", "''") + "','Email Attachment','" + getMimeType(System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName)).Replace("'", "''") + "'," + len + ",'" + System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName).Replace("'", "''") + "','<a href=''documents.aspx?file=" + af_row_id + "''>" + System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName).Replace("'", "''") + "</a>','" + af_row_id + "','" + Session["user_afrowid"].ToString() + "','" + DateTime.UtcNow + "','" + DateTime.UtcNow + "','" + Session["user_afrowid"].ToString() + "',@pcont,'" + Session["user_afrowid"].ToString() + "','" + related_af_row_id + "')";

                    SqlCommand sc = new SqlCommand(sql);
                    SqlParameter sp = new SqlParameter("@pcont", SqlDbType.VarBinary, len);
                    FileUpload1.PostedFile.InputStream.Close();
                    sp.Value = filea;
                    sc.Parameters.Add(sp);
                    HDD.ExecuteCmdObj(sc);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : SaveAttachmentsinDocument : " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return status;
    }

    private bool validFile()
    {
        string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower();
        string[] invalids = new string[] { ".exe", ".dll", ".ocx", ".bat" };
        for (int i = 0; i < invalids.Length; i++)
        {
            if (ext.IndexOf(invalids[i]) > -1)
                return false;
        }
        return true;

    }
    
    private string getMimeType(string fileExtension)//included by sanal on 25Mar09 for file_type/mime type
    {
        string retval = "";
        //switch (Systm.IO.Path.GetExtension(strFileName).ToLower())
        switch (fileExtension.ToLower())
        {
            case ".3dm": retval = "x-world/x-3dmf"; break;
            case ".3dmf": retval = "x-world/x-3dmf"; break;
            case ".a": retval = "application/octet-stream"; break;
            case ".aab": retval = "application/x-authorware-bin"; break;
            case ".aam": retval = "application/x-authorware-map"; break;
            case ".aas": retval = "application/x-authorware-seg"; break;
            case ".abc": retval = "text/vnd.abc"; break;
            case ".acgi": retval = "text/html"; break;
            case ".afl": retval = "video/animaflex"; break;
            case ".ai": retval = "application/postscript"; break;
            case ".aif": retval = "audio/aiff"; break;
            case ".aifc": retval = "audio/aiff"; break;
            case ".aiff": retval = "audio/aiff"; break;
            case ".aim": retval = "application/x-aim"; break;
            case ".aip": retval = "text/x-audiosoft-intra"; break;
            case ".ani": retval = "application/x-navi-animation"; break;
            case ".aos": retval = "application/x-nokia-9000-communicator-add-on-software"; break;
            case ".aps": retval = "application/mime"; break;
            case ".arc": retval = "application/octet-stream"; break;
            case ".arj": retval = "application/arj"; break;
            case ".art": retval = "image/x-jg"; break;
            case ".asf": retval = "video/x-ms-asf"; break;
            case ".asm": retval = "text/x-asm"; break;
            case ".asp": retval = "text/asp"; break;
            case ".asx": retval = "video/x-ms-asf"; break;
            case ".au": retval = "audio/basic"; break;
            case ".avi": retval = "video/avi"; break;
            case ".avs": retval = "video/avs-video"; break;
            case ".bcpio": retval = "application/x-bcpio"; break;
            case ".bin": retval = "application/octet-stream"; break;
            case ".bm": retval = "image/bmp"; break;
            case ".bmp": retval = "image/bmp"; break;
            case ".boo": retval = "application/book"; break;
            case ".book": retval = "application/book"; break;
            case ".boz": retval = "application/x-bzip2"; break;
            case ".bsh": retval = "application/x-bsh"; break;
            case ".bz": retval = "application/x-bzip"; break;
            case ".bz2": retval = "application/x-bzip2"; break;
            case ".c": retval = "text/plain"; break;
            case ".c++": retval = "text/plain"; break;
            case ".cat": retval = "application/vnd.ms-pki.seccat"; break;
            case ".cc": retval = "text/plain"; break;
            case ".ccad": retval = "application/clariscad"; break;
            case ".cco": retval = "application/x-cocoa"; break;
            case ".cdf": retval = "application/cdf"; break;
            case ".cer": retval = "application/pkix-cert"; break;
            case ".cha": retval = "application/x-chat"; break;
            case ".chat": retval = "application/x-chat"; break;
            case ".class": retval = "application/java"; break;
            case ".com": retval = "application/octet-stream"; break;
            case ".conf": retval = "text/plain"; break;
            case ".cpio": retval = "application/x-cpio"; break;
            case ".cpp": retval = "text/x-c"; break;
            case ".cpt": retval = "application/x-cpt"; break;
            case ".crl": retval = "application/pkcs-crl"; break;
            case ".crt": retval = "application/pkix-cert"; break;
            case ".csh": retval = "application/x-csh"; break;
            case ".css": retval = "text/css"; break;
            case ".cxx": retval = "text/plain"; break;
            case ".dcr": retval = "application/x-director"; break;
            case ".deepv": retval = "application/x-deepv"; break;
            case ".def": retval = "text/plain"; break;
            case ".der": retval = "application/x-x509-ca-cert"; break;
            case ".dif": retval = "video/x-dv"; break;
            case ".dir": retval = "application/x-director"; break;
            case ".dl": retval = "video/dl"; break;
            case ".doc": retval = "application/msword"; break;
            case ".dot": retval = "application/msword"; break;
            case ".dp": retval = "application/commonground"; break;
            case ".drw": retval = "application/drafting"; break;
            case ".dump": retval = "application/octet-stream"; break;
            case ".dv": retval = "video/x-dv"; break;
            case ".dvi": retval = "application/x-dvi"; break;
            case ".dwf": retval = "model/vnd.dwf"; break;
            case ".dwg": retval = "image/vnd.dwg"; break;
            case ".dxf": retval = "image/vnd.dwg"; break;
            case ".dxr": retval = "application/x-director"; break;
            case ".el": retval = "text/x-script.elisp"; break;
            case ".elc": retval = "application/x-elc"; break;
            case ".env": retval = "application/x-envoy"; break;
            case ".eps": retval = "application/postscript"; break;
            case ".es": retval = "application/x-esrehber"; break;
            case ".etx": retval = "text/x-setext"; break;
            case ".evy": retval = "application/envoy"; break;
            case ".exe": retval = "application/octet-stream"; break;
            case ".f": retval = "text/plain"; break;
            case ".f77": retval = "text/x-fortran"; break;
            case ".f90": retval = "text/plain"; break;
            case ".fdf": retval = "application/vnd.fdf"; break;
            case ".fif": retval = "image/fif"; break;
            case ".fli": retval = "video/fli"; break;
            case ".flo": retval = "image/florian"; break;
            case ".flx": retval = "text/vnd.fmi.flexstor"; break;
            case ".fmf": retval = "video/x-atomic3d-feature"; break;
            case ".for": retval = "text/x-fortran"; break;
            case ".fpx": retval = "image/vnd.fpx"; break;
            case ".frl": retval = "application/freeloader"; break;
            case ".funk": retval = "audio/make"; break;
            case ".g": retval = "text/plain"; break;
            case ".g3": retval = "image/g3fax"; break;
            case ".gif": retval = "image/gif"; break;
            case ".gl": retval = "video/gl"; break;
            case ".gsd": retval = "audio/x-gsm"; break;
            case ".gsm": retval = "audio/x-gsm"; break;
            case ".gsp": retval = "application/x-gsp"; break;
            case ".gss": retval = "application/x-gss"; break;
            case ".gtar": retval = "application/x-gtar"; break;
            case ".gz": retval = "application/x-gzip"; break;
            case ".gzip": retval = "application/x-gzip"; break;
            case ".h": retval = "text/plain"; break;
            case ".hdf": retval = "application/x-hdf"; break;
            case ".help": retval = "application/x-helpfile"; break;
            case ".hgl": retval = "application/vnd.hp-hpgl"; break;
            case ".hh": retval = "text/plain"; break;
            case ".hlb": retval = "text/x-script"; break;
            case ".hlp": retval = "application/hlp"; break;
            case ".hpg": retval = "application/vnd.hp-hpgl"; break;
            case ".hpgl": retval = "application/vnd.hp-hpgl"; break;
            case ".hqx": retval = "application/binhex"; break;
            case ".hta": retval = "application/hta"; break;
            case ".htc": retval = "text/x-component"; break;
            case ".htm": retval = "text/html"; break;
            case ".html": retval = "text/html"; break;
            case ".htmls": retval = "text/html"; break;
            case ".htt": retval = "text/webviewhtml"; break;
            case ".htx": retval = "text/html"; break;
            case ".ice": retval = "x-conference/x-cooltalk"; break;
            case ".ico": retval = "image/x-icon"; break;
            case ".idc": retval = "text/plain"; break;
            case ".ief": retval = "image/ief"; break;
            case ".iefs": retval = "image/ief"; break;
            case ".iges": retval = "application/iges"; break;
            case ".igs": retval = "application/iges"; break;
            case ".ima": retval = "application/x-ima"; break;
            case ".imap": retval = "application/x-httpd-imap"; break;
            case ".inf": retval = "application/inf"; break;
            case ".ins": retval = "application/x-internett-signup"; break;
            case ".ip": retval = "application/x-ip2"; break;
            case ".isu": retval = "video/x-isvideo"; break;
            case ".it": retval = "audio/it"; break;
            case ".iv": retval = "application/x-inventor"; break;
            case ".ivr": retval = "i-world/i-vrml"; break;
            case ".ivy": retval = "application/x-livescreen"; break;
            case ".jam": retval = "audio/x-jam"; break;
            case ".jav": retval = "text/plain"; break;
            case ".java": retval = "text/plain"; break;
            case ".jcm": retval = "application/x-java-commerce"; break;
            case ".jfif": retval = "image/jpeg"; break;
            case ".jfif-tbnl": retval = "image/jpeg"; break;
            case ".jpe": retval = "image/jpeg"; break;
            case ".jpeg": retval = "image/jpeg"; break;
            case ".jpg": retval = "image/jpeg"; break;
            case ".jps": retval = "image/x-jps"; break;
            case ".js": retval = "application/x-javascript"; break;
            case ".jut": retval = "image/jutvision"; break;
            case ".kar": retval = "audio/midi"; break;
            case ".ksh": retval = "application/x-ksh"; break;
            case ".la": retval = "audio/nspaudio"; break;
            case ".lam": retval = "audio/x-liveaudio"; break;
            case ".latex": retval = "application/x-latex"; break;
            case ".lha": retval = "application/octet-stream"; break;
            case ".lhx": retval = "application/octet-stream"; break;
            case ".list": retval = "text/plain"; break;
            case ".lma": retval = "audio/nspaudio"; break;
            case ".log": retval = "text/plain"; break;
            case ".lsp": retval = "application/x-lisp"; break;
            case ".lst": retval = "text/plain"; break;
            case ".lsx": retval = "text/x-la-asf"; break;
            case ".ltx": retval = "application/x-latex"; break;
            case ".lzh": retval = "application/octet-stream"; break;
            case ".lzx": retval = "application/octet-stream"; break;
            case ".m": retval = "text/plain"; break;
            case ".m1v": retval = "video/mpeg"; break;
            case ".m2a": retval = "audio/mpeg"; break;
            case ".m2v": retval = "video/mpeg"; break;
            case ".m3u": retval = "audio/x-mpequrl"; break;
            case ".man": retval = "application/x-troff-man"; break;
            case ".map": retval = "application/x-navimap"; break;
            case ".mar": retval = "text/plain"; break;
            case ".mbd": retval = "application/mbedlet"; break;
            case ".mc$": retval = "application/x-magic-cap-package-1.0"; break;
            case ".mcd": retval = "application/mcad"; break;
            case ".mcf": retval = "text/mcf"; break;
            case ".mcp": retval = "application/netmc"; break;
            case ".me": retval = "application/x-troff-me"; break;
            case ".mht": retval = "message/rfc822"; break;
            case ".mhtml": retval = "message/rfc822"; break;
            case ".mid": retval = "audio/midi"; break;
            case ".midi": retval = "audio/midi"; break;
            case ".mif": retval = "application/x-mif"; break;
            case ".mime": retval = "message/rfc822"; break;
            case ".mjf": retval = "audio/x-vnd.audioexplosion.mjuicemediafile"; break;
            case ".mjpg": retval = "video/x-motion-jpeg"; break;
            case ".mm": retval = "application/base64"; break;
            case ".mme": retval = "application/base64"; break;
            case ".mod": retval = "audio/mod"; break;
            case ".moov": retval = "video/quicktime"; break;
            case ".mov": retval = "video/quicktime"; break;
            case ".movie": retval = "video/x-sgi-movie"; break;
            case ".mp2": retval = "audio/mpeg"; break;
            case ".mp3": retval = "audio/mpeg"; break;
            case ".mpa": retval = "audio/mpeg"; break;
            case ".mpc": retval = "application/x-project"; break;
            case ".mpe": retval = "video/mpeg"; break;
            case ".mpeg": retval = "video/mpeg"; break;
            case ".mpg": retval = "video/mpeg"; break;
            case ".mpga": retval = "audio/mpeg"; break;
            case ".mpp": retval = "application/vnd.ms-project"; break;
            case ".mpt": retval = "application/vnd.ms-project"; break;
            case ".mpv": retval = "application/vnd.ms-project"; break;
            case ".mpx": retval = "application/vnd.ms-project"; break;
            case ".mrc": retval = "application/marc"; break;
            case ".ms": retval = "application/x-troff-ms"; break;
            case ".mv": retval = "video/x-sgi-movie"; break;
            case ".my": retval = "audio/make"; break;
            case ".mzz": retval = "application/x-vnd.audioexplosion.mzz"; break;
            case ".nap": retval = "image/naplps"; break;
            case ".naplps": retval = "image/naplps"; break;
            case ".nc": retval = "application/x-netcdf"; break;
            case ".ncm": retval = "application/vnd.nokia.configuration-message"; break;
            case ".nif": retval = "image/x-niff"; break;
            case ".niff": retval = "image/x-niff"; break;
            case ".nix": retval = "application/x-mix-transfer"; break;
            case ".nsc": retval = "application/x-conference"; break;
            case ".nvd": retval = "application/x-navidoc"; break;
            case ".o": retval = "application/octet-stream"; break;
            case ".oda": retval = "application/oda"; break;
            case ".omc": retval = "application/x-omc"; break;
            case ".omcd": retval = "application/x-omcdatamaker"; break;
            case ".omcr": retval = "application/x-omcregerator"; break;
            case ".p": retval = "text/x-pascal"; break;
            case ".p10": retval = "application/pkcs10"; break;
            case ".p12": retval = "application/pkcs-12"; break;
            case ".p7a": retval = "application/x-pkcs7-signature"; break;
            case ".p7c": retval = "application/pkcs7-mime"; break;
            case ".p7m": retval = "application/pkcs7-mime"; break;
            case ".p7r": retval = "application/x-pkcs7-certreqresp"; break;
            case ".p7s": retval = "application/pkcs7-signature"; break;
            case ".part": retval = "application/pro_eng"; break;
            case ".pas": retval = "text/pascal"; break;
            case ".pbm": retval = "image/x-portable-bitmap"; break;
            case ".pcl": retval = "application/vnd.hp-pcl"; break;
            case ".pct": retval = "image/x-pict"; break;
            case ".pcx": retval = "image/x-pcx"; break;
            case ".pdb": retval = "chemical/x-pdb"; break;
            case ".pdf": retval = "application/pdf"; break;
            case ".pfunk": retval = "audio/make"; break;
            case ".pgm": retval = "image/x-portable-greymap"; break;
            case ".pic": retval = "image/pict"; break;
            case ".pict": retval = "image/pict"; break;
            case ".pkg": retval = "application/x-newton-compatible-pkg"; break;
            case ".pko": retval = "application/vnd.ms-pki.pko"; break;
            case ".pl": retval = "text/plain"; break;
            case ".plx": retval = "application/x-pixclscript"; break;
            case ".pm": retval = "image/x-xpixmap"; break;
            case ".pm4": retval = "application/x-pagemaker"; break;
            case ".pm5": retval = "application/x-pagemaker"; break;
            case ".png": retval = "image/png"; break;
            case ".pnm": retval = "application/x-portable-anymap"; break;
            case ".pot": retval = "application/vnd.ms-powerpoint"; break;
            case ".pov": retval = "model/x-pov"; break;
            case ".ppa": retval = "application/vnd.ms-powerpoint"; break;
            case ".ppm": retval = "image/x-portable-pixmap"; break;
            case ".pps": retval = "application/vnd.ms-powerpoint"; break;
            case ".ppt": retval = "application/vnd.ms-powerpoint"; break;
            case ".ppz": retval = "application/vnd.ms-powerpoint"; break;
            case ".pre": retval = "application/x-freelance"; break;
            case ".prt": retval = "application/pro_eng"; break;
            case ".ps": retval = "application/postscript"; break;
            case ".psd": retval = "application/octet-stream"; break;
            case ".pvu": retval = "paleovu/x-pv"; break;
            case ".pwz": retval = "application/vnd.ms-powerpoint"; break;
            case ".py": retval = "text/x-script.phyton"; break;
            case ".pyc": retval = "applicaiton/x-bytecode.python"; break;
            case ".qcp": retval = "audio/vnd.qcelp"; break;
            case ".qd3": retval = "x-world/x-3dmf"; break;
            case ".qd3d": retval = "x-world/x-3dmf"; break;
            case ".qif": retval = "image/x-quicktime"; break;
            case ".qt": retval = "video/quicktime"; break;
            case ".qtc": retval = "video/x-qtc"; break;
            case ".qti": retval = "image/x-quicktime"; break;
            case ".qtif": retval = "image/x-quicktime"; break;
            case ".ra": retval = "audio/x-pn-realaudio"; break;
            case ".ram": retval = "audio/x-pn-realaudio"; break;
            case ".ras": retval = "application/x-cmu-raster"; break;
            case ".rast": retval = "image/cmu-raster"; break;
            case ".rexx": retval = "text/x-script.rexx"; break;
            case ".rf": retval = "image/vnd.rn-realflash"; break;
            case ".rgb": retval = "image/x-rgb"; break;
            case ".rm": retval = "application/vnd.rn-realmedia"; break;
            case ".rmi": retval = "audio/mid"; break;
            case ".rmm": retval = "audio/x-pn-realaudio"; break;
            case ".rmp": retval = "audio/x-pn-realaudio"; break;
            case ".rng": retval = "application/ringing-tones"; break;
            case ".rnx": retval = "application/vnd.rn-realplayer"; break;
            case ".roff": retval = "application/x-troff"; break;
            case ".rp": retval = "image/vnd.rn-realpix"; break;
            case ".rpm": retval = "audio/x-pn-realaudio-plugin"; break;
            case ".rt": retval = "text/richtext"; break;
            case ".rtf": retval = "text/richtext"; break;
            case ".rtx": retval = "text/richtext"; break;
            case ".rv": retval = "video/vnd.rn-realvideo"; break;
            case ".s": retval = "text/x-asm"; break;
            case ".s3m": retval = "audio/s3m"; break;
            case ".saveme": retval = "application/octet-stream"; break;
            case ".sbk": retval = "application/x-tbook"; break;
            case ".scm": retval = "application/x-lotusscreencam"; break;
            case ".sdml": retval = "text/plain"; break;
            case ".sdp": retval = "application/sdp"; break;
            case ".sdr": retval = "application/sounder"; break;
            case ".sea": retval = "application/sea"; break;
            case ".set": retval = "application/set"; break;
            case ".sgm": retval = "text/sgml"; break;
            case ".sgml": retval = "text/sgml"; break;
            case ".sh": retval = "application/x-sh"; break;
            case ".shar": retval = "application/x-shar"; break;
            case ".shtml": retval = "text/html"; break;
            case ".sid": retval = "audio/x-psid"; break;
            case ".sit": retval = "application/x-sit"; break;
            case ".skd": retval = "application/x-koan"; break;
            case ".skm": retval = "application/x-koan"; break;
            case ".skp": retval = "application/x-koan"; break;
            case ".skt": retval = "application/x-koan"; break;
            case ".sl": retval = "application/x-seelogo"; break;
            case ".smi": retval = "application/smil"; break;
            case ".smil": retval = "application/smil"; break;
            case ".snd": retval = "audio/basic"; break;
            case ".sol": retval = "application/solids"; break;
            case ".spc": retval = "text/x-speech"; break;
            case ".spl": retval = "application/futuresplash"; break;
            case ".spr": retval = "application/x-sprite"; break;
            case ".sprite": retval = "application/x-sprite"; break;
            case ".src": retval = "application/x-wais-source"; break;
            case ".ssi": retval = "text/x-server-parsed-html"; break;
            case ".ssm": retval = "application/streamingmedia"; break;
            case ".sst": retval = "application/vnd.ms-pki.certstore"; break;
            case ".step": retval = "application/step"; break;
            case ".stl": retval = "application/sla"; break;
            case ".stp": retval = "application/step"; break;
            case ".sv4cpio": retval = "application/x-sv4cpio"; break;
            case ".sv4crc": retval = "application/x-sv4crc"; break;
            case ".svf": retval = "image/vnd.dwg"; break;
            case ".svr": retval = "application/x-world"; break;
            case ".swf": retval = "application/x-shockwave-flash"; break;
            case ".t": retval = "application/x-troff"; break;
            case ".talk": retval = "text/x-speech"; break;
            case ".tar": retval = "application/x-tar"; break;
            case ".tbk": retval = "application/toolbook"; break;
            case ".tcl": retval = "application/x-tcl"; break;
            case ".tcsh": retval = "text/x-script.tcsh"; break;
            case ".tex": retval = "application/x-tex"; break;
            case ".texi": retval = "application/x-texinfo"; break;
            case ".texinfo": retval = "application/x-texinfo"; break;
            case ".text": retval = "text/plain"; break;
            case ".tgz": retval = "application/x-compressed"; break;
            case ".tif": retval = "image/tiff"; break;
            case ".tiff": retval = "image/tiff"; break;
            case ".tr": retval = "application/x-troff"; break;
            case ".tsi": retval = "audio/tsp-audio"; break;
            case ".tsp": retval = "application/dsptype"; break;
            case ".tsv": retval = "text/tab-separated-values"; break;
            case ".turbot": retval = "image/florian"; break;
            case ".txt": retval = "text/plain"; break;
            case ".uil": retval = "text/x-uil"; break;
            case ".uni": retval = "text/uri-list"; break;
            case ".unis": retval = "text/uri-list"; break;
            case ".unv": retval = "application/i-deas"; break;
            case ".uri": retval = "text/uri-list"; break;
            case ".uris": retval = "text/uri-list"; break;
            case ".ustar": retval = "application/x-ustar"; break;
            case ".uu": retval = "application/octet-stream"; break;
            case ".uue": retval = "text/x-uuencode"; break;
            case ".vcd": retval = "application/x-cdlink"; break;
            case ".vcs": retval = "text/x-vcalendar"; break;
            case ".vda": retval = "application/vda"; break;
            case ".vdo": retval = "video/vdo"; break;
            case ".vew": retval = "application/groupwise"; break;
            case ".viv": retval = "video/vivo"; break;
            case ".vivo": retval = "video/vivo"; break;
            case ".vmd": retval = "application/vocaltec-media-desc"; break;
            case ".vmf": retval = "application/vocaltec-media-file"; break;
            case ".voc": retval = "audio/voc"; break;
            case ".vos": retval = "video/vosaic"; break;
            case ".vox": retval = "audio/voxware"; break;
            case ".vqe": retval = "audio/x-twinvq-plugin"; break;
            case ".vqf": retval = "audio/x-twinvq"; break;
            case ".vql": retval = "audio/x-twinvq-plugin"; break;
            case ".vrml": retval = "application/x-vrml"; break;
            case ".vrt": retval = "x-world/x-vrt"; break;
            case ".vsd": retval = "application/x-visio"; break;
            case ".vst": retval = "application/x-visio"; break;
            case ".vsw": retval = "application/x-visio"; break;
            case ".w60": retval = "application/wordperfect6.0"; break;
            case ".w61": retval = "application/wordperfect6.1"; break;
            case ".w6w": retval = "application/msword"; break;
            case ".wav": retval = "audio/wav"; break;
            case ".wb1": retval = "application/x-qpro"; break;
            case ".wbmp": retval = "image/vnd.wap.wbmp"; break;
            case ".web": retval = "application/vnd.xara"; break;
            case ".wiz": retval = "application/msword"; break;
            case ".wk1": retval = "application/x-123"; break;
            case ".wmf": retval = "windows/metafile"; break;
            case ".wml": retval = "text/vnd.wap.wml"; break;
            case ".wmlc": retval = "application/vnd.wap.wmlc"; break;
            case ".wmls": retval = "text/vnd.wap.wmlscript"; break;
            case ".wmlsc": retval = "application/vnd.wap.wmlscriptc"; break;
            case ".word": retval = "application/msword"; break;
            case ".wp": retval = "application/wordperfect"; break;
            case ".wp5": retval = "application/wordperfect"; break;
            case ".wp6": retval = "application/wordperfect"; break;
            case ".wpd": retval = "application/wordperfect"; break;
            case ".wq1": retval = "application/x-lotus"; break;
            case ".wri": retval = "application/mswrite"; break;
            case ".wrl": retval = "application/x-world"; break;
            case ".wrz": retval = "x-world/x-vrml"; break;
            case ".wsc": retval = "text/scriplet"; break;
            case ".wsrc": retval = "application/x-wais-source"; break;
            case ".wtk": retval = "application/x-wintalk"; break;
            case ".xbm": retval = "image/x-xbitmap"; break;
            case ".xdr": retval = "video/x-amt-demorun"; break;
            case ".xgz": retval = "xgl/drawing"; break;
            case ".xif": retval = "image/vnd.xiff"; break;
            case ".xl": retval = "application/excel"; break;
            case ".xla": retval = "application/vnd.ms-excel"; break;
            case ".xlb": retval = "application/vnd.ms-excel"; break;
            case ".xlc": retval = "application/vnd.ms-excel"; break;
            case ".xld": retval = "application/vnd.ms-excel"; break;
            case ".xlk": retval = "application/vnd.ms-excel"; break;
            case ".xll": retval = "application/vnd.ms-excel"; break;
            case ".xlm": retval = "application/vnd.ms-excel"; break;
            case ".xls": retval = "application/vnd.ms-excel"; break;
            case ".xlt": retval = "application/vnd.ms-excel"; break;
            case ".xlv": retval = "application/vnd.ms-excel"; break;
            case ".xlw": retval = "application/vnd.ms-excel"; break;
            case ".xm": retval = "audio/xm"; break;
            case ".xml": retval = "application/xml"; break;
            case ".xmz": retval = "xgl/movie"; break;
            case ".xpix": retval = "application/x-vnd.ls-xpix"; break;
            case ".xpm": retval = "image/xpm"; break;
            case ".x-png": retval = "image/png"; break;
            case ".xsr": retval = "video/x-amt-showrun"; break;
            case ".xwd": retval = "image/x-xwd"; break;
            case ".xyz": retval = "chemical/x-pdb"; break;
            case ".z": retval = "application/x-compressed"; break;
            case ".zip": retval = "application/zip"; break;
            case ".zoo": retval = "application/octet-stream"; break;
            case ".zsh": retval = "text/x-script.zsh"; break;
            default: retval = "application/octet-stream"; break;
        }
        return retval;
    }
//function NavigateEmailPage(pgs_id,mn,PK,Emailfield,FirstField,mode)
//{
//    try
//    {
//        var strEFval = "";
//        var strFFval ="";
//        if(mode==1) //list
//        {
//            strEFval = Emailfield;
//            strFFval = FirstField
//        }
//        else if(mode==2) //Edit View mode
//        {
//            if(document.getElementById(Emailfield)!=null)
//            {
//                alert("found email field");
//            }
//            if(document.getElementById(FirstField)!=null)
//            {
//                alert("first Field found");
//            }   
//        }
    //        window.location.href = "ComposeEmail.aspx?pgs_id="+pgs_id+"&mn="+mn+"&PK="+PK+"&EF="+strEFval+"&FF="+strFFval+"";
//    }
//    catch(ex)
//    {
//    }
//}

    protected void btnSendTop_Click1(object sender, EventArgs e)
    {
        SendEmail();
    }
    private void HidePanels()
    {
        try
        {
            tblAttachments.Style.Add("display", "none");
            tblCC.Style.Add("display", "none");
            tblBCC.Style.Add("display","none");
            //style="display:none;"
        }
        catch
        {
        }
    }

    private bool ValidateEmailID(string firstfield,string tablename)
    {
        bool status = false;
        HDDatabase HDD = new HDDatabase();
        SecurityFilter SF = new SecurityFilter();
        try
        {

            DataRow drMasterChild = GetMasterChildRecord();
            string sql = "";
            if (drMasterChild != null)
            {
                string strMasterTableName = HDD.GetColumnValue("select object_table from sy_obj where object_id = '"+drMasterChild["master_obj"].ToString()+"'");
                sql = "select " + strEmailField + " as EF,  (select " + drMasterChild["display_att"].ToString() + " from "+strMasterTableName+" where af_row_id =  A." + firstfield + ") as FF from " + tablename + " A where " + strEmailField + " is not null";
            }
            else
            {
                sql = "select " + strEmailField + " as EF, " + firstfield + " as FF from " + tablename + " where " + strEmailField + " is not null";
            }
            sql = SF.applysecurity(sql);
            DataTable dt = HDD.GetDataTable(sql);
            if(dt!=null)
                if(dt.Rows.Count>0)
                {
                    //if (hfTo.Value.Trim() == "")
                    //{
                    string strtofield = "";
                    if (txtTo.Text.Trim() == "")
                        strtofield = string.Empty;
                    else
                        strtofield = txtTo.Text.Trim();

                    DataRow[] drr = dt.Select("FF='" + strtofield.Replace("'", "''") + "'");
                        if (drr.Length > 0)
                        {
                            hfTo.Value = drr[0]["EF"].ToString();
                            status = true;
                        }
                    //}
                    //else
                    //{
                    //    DataRow[] drr = dt.Select("FF='" + txtTo.Text.Trim().Replace("'","''") + "' and EF = '" + hfTo.Value.Replace("'","''") + "'");
                    //    if (drr.Length > 0)
                    //    {
                    //        status = true;
                    //    }
                    //}
                }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : ValidateEmailID : "+ex.Message);
        }
        finally
        {
            HDD = null;
            SF = null;
        }

        return status;
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        string url = Navigator.getURL(Request.Url.ToString());
        Response.Redirect(url);
    }
    protected void btnCancelTop_Click(object sender, EventArgs e)
    {
        string url = Navigator.getURL(Request.Url.ToString());
        Response.Redirect(url);
    }

    private void ReEnableButtons()
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        try
        {
            DDI.setAttribute(txtTo.Attributes, "onchange", "javascript:ReEnableSendButton();");
            DDI.setAttribute(txtSubject.Attributes, "onchange", "javascript:ReEnableSendButton();");
            DDI.setAttribute(txtBody.Attributes, "onchange", "javascript:ReEnableSendButton();");
            DDI.setAttribute(txtCC.Attributes, "onchange", "javascript:ReEnableSendButton();");
            DDI.setAttribute(txtBCC.Attributes, "onchange", "javascript:ReEnableSendButton();");
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : ReEnableButtons :" + ex.Message);
        }
        finally
        {
            DDI = null;
        }
    }

    private bool CheckIfBCCExists()
    {
        DynamicDisplayI DDI = new DynamicDisplayI();
        bool status = false;
        try
        {
            //string style = tblBCC.Style.Value;
            //if (style.ToLower().Contains("display:none"))
            //{
            //    status = false;
            //}
            if (hfshowBCC.Value.Trim() != "")
            {
                if (hfshowBCC.Value == "1")
                {
                    status = true;
                }
            }
        }
        catch
        { }
        finally
        {
            DDI = null;
        }
        return status;
    }

    private bool ValidateAttachments()
    {
        bool status = true;
        try
        {
            if (FileUpload1.HasFile)
                if(FileUpload1.PostedFile.FileName.Length>0)
                {
                    int len = FileUpload1.PostedFile.ContentLength;
                    if (len > 4096000)
                        status = false;
                }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : ValidateAttachments : "+ ex.Message);
        }
        return status;
    }
    private void ReEnablePanels()
    {
        if (hfshowCC.Value == "1")
        {
            tblCC.Style.Add("display", "block");
            lnkCC.Text = "Remove CC";
        }
        if (hfshowBCC.Value == "1")
        {
            tblBCC.Style.Add("display", "block");
            lnkBCC.Text = "Remove BCC";
        }
        if (hfshowAttach.Value == "1")
            tblAttachments.Style.Add("display","block");
    }
    private void UpdateRelatedTo()
    {
        try
        {
            string relatedto = txtRelatedTo.Text;
            if (relatedto.Contains(":"))
            {
                string temp = relatedto.Substring(0, relatedto.IndexOf(":"));
                txtRelatedTo.Text = temp +" : "+ txtTo.Text;
            }

        }
        catch
        {

        }
    }

    private DataRow GetMasterChildRecord()
    {
        DataRow drResult = null;
        HDDatabase HDD = new HDDatabase();
        try
        {
            if(Request.QueryString["pgs_id"]!=null)
            {
                string sql = "select * from sy_obj_mas_Detail where object_id in (select top 1 af_row_id from sy_obj where object_id in (select object_id from sy_pgs A, sy_pgs_mem B where A.af_row_id = B.pageset_id and A.af_row_id = '" + Request.QueryString["pgs_id"].ToString() + "'))";
                drResult = HDD.GetTableRow(sql);
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetMasterChildRecord :"+ ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return drResult;
    }
}
